<?php

declare(strict_types=1);

namespace App\Service;

use App\Constants\ErrorCode;
use App\Exception\BusinessException;
use App\Library\Common;
use App\Model\FlyShop;
use App\Model\FlyShopApply;
use App\Model\FlyShopApplysInfo;
use App\Model\FlyShopCertificate;
use App\Model\FlyShopCertificateAtt;
use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Hyperf\Validation\Contract\ValidatorFactoryInterface;
use Hyperf\Validation\Rule;
use Hyperf\Di\Annotation\Inject;

/**
 * 商家入驻服务
 * Class MerchantJoinService
 * @package App\Service
 */
class MerchantJoinService
{

    /**
     * @Inject
     * @var FlyShopCertificateAttService
     */
    private $certAtt;

    /**
     * @Inject
     * @var DistributionCenterService
     */
    protected $dc;

    /**
     * @Inject()
     * @var ValidatorFactoryInterface
     */
    protected $validator;

    /**
     * @Inject
     * @var FileinfoService
     */
    protected $fileinfo;

    /**
     * @Inject
     * @var FlyShopService
     */
    protected $flyShop;

    /**
     * @Inject
     * @var IndustryService
     */
    protected $industry;

    /**
     * @Inject
     * @var FlyShopApplyService
     */
    protected $flyShopApply;

    /**
     * @Inject
     * @var FlyShopApplysInfoService
     */
    protected $flyShopApplyInfo;

    /**
     * 验证有效信息
     * @param array $data
     * @param int $user_id
     * @return array
     */
    public function merchant_verify(array $data, int $user_id): array
    {
        // 申请类型 1申请入驻 2完善信息 3店铺修改信息 4入驻单修改信息
        $type = empty($data['apply_order_type']) ? 1 : $data['apply_order_type'];
        // 获取过滤参数及基本验证
        $filter_data = $this->merchant_filter_params($data, $type);
        $valid = $this->validator->make(
            $filter_data['params'],
            $filter_data['rules']
        );
        $res = true;
        $msg = "";
        // 入驻申请、修改重新入驻、修改店铺认证信息
        if (in_array($type, [1, 3, 4]) && empty($filter_data['params']['shop_type'])) {
            throw new BusinessException(ErrorCode::NORMAL_ERROR, '未选择入驻类型');
        }

        if ($valid->fails()) {
            throw new BusinessException(ErrorCode::NORMAL_ERROR, $valid->errors()->first());
        }

        $join_in_flag = 0;
        // 需单独处理或验证
        if ($type == 1) {
            if ($this->flyShop->checkShopName($filter_data['params']['shop_name'], true, $user_id)) {
                throw new BusinessException(ErrorCode::NORMAL_ERROR, '店铺已存在');
            }
            $my_shop = $this->flyShop->getMyShop($user_id);
            // 需判断入驻商城类型：可能已入驻美食
            if (!empty($my_shop) && !empty($my_shop['type'])) {
                throw new BusinessException(ErrorCode::NORMAL_ERROR, '重复操作，已申请入驻');
            }

            // 存在申请单（完善提交、待通过、待驳回）
            $apply_check = $this->flyShopApply->getInstance()->where(function ($where) use ($user_id) {
                $where->where('user_id', '=', $user_id)
                    ->where('shop_style', '=', FlyShopService::STYLE_TYPE_SHOP)
                    ->whereIn('status', [0, 1, 2]);
            })->first();
            if (!empty($apply_check)) {
                throw new BusinessException(ErrorCode::NORMAL_ERROR, "无法申请，存在待完善的申请单");
            }

        } else {
            // 完善或重新入驻
            if (empty($filter_data['params']['figure_ids']) || !is_array($filter_data['params']['figure_ids'])) {
                throw new BusinessException(ErrorCode::NORMAL_ERROR, '未上传门店信息');
            }

            if ($type == 3) {
                // 编辑 可以设置多个集散地
                $filter_data['params']['dc'] = $this->dc->getDcArrayByIds($filter_data['params']['dc_ids'], ['id', 'name']);// todo 非必要字段
            } else {
                // 获取集散地 dc_ids -> dc_list
                $filter_data['params']['dc'] = $this->dc->getDcArrayById((int)$filter_data['params']['dc_id'], ['id', 'name']);// todo 非必要字段
            }
            $filter_data['params']['dc_list'] = json_encode($filter_data['params']['dc'], 256);

            // 完善信息
            if ($type == 2 || $type == 4) {

                // 验证门店信息
                $figure_ids = $filter_data['params']['figure_ids'];
                $figures = $this->fileinfo->getFileinfo($figure_ids);
                if (empty($figures) || count($figures) != count($figure_ids)) {
                    throw new BusinessException(ErrorCode::NORMAL_ERROR, '存在无效图片');
                }
                $figures_arr = [];
                foreach ($figures as $figure) {
                    if ($figure['user_id'] != $user_id) {
                        throw new BusinessException(ErrorCode::NORMAL_ERROR, '存在无效图片2');
                    }
                    $figures_arr[] = [
                        'url' => Common::cdnurl($figure['url']),
                        'fileinfo_id' => $figure['fileinfo_id']
                    ];
                }
                $filter_data['params']['figure_str'] = json_encode($figures_arr, JSON_PARTIAL_OUTPUT_ON_ERROR);

                // 重新入驻提交
                if ($type == 4) {
                    // 存在未审核的入驻申请单
                    if ($this->flyShopApply->getInstance()->where(['user_id' => $user_id, 'status' => 2, 'shop_style' => 1])->exists()) {
                        throw new BusinessException(ErrorCode::NORMAL_ERROR, '入驻单已审核通过');
                    }
                    // 店铺名称唯一验证
                    if ($this->flyShop->checkShopName($filter_data['params']['shop_name'], true, $user_id)) {
                        throw new BusinessException(ErrorCode::NORMAL_ERROR, "店铺已存在");
                    }
                    // 集散地验证
                    if (empty($this->dc->getDcArrayById($filter_data['params']['dc_id'], ['id', 'name']))) {
                        throw new BusinessException(ErrorCode::NORMAL_ERROR, '集散地不存在');
                    }
                    // 是否存在申请单
                    $apply_check = $this->flyShopApply->getInstance()->where(function ($where) use ($user_id) {
                        $where->where('user_id', '=', $user_id)
                            ->where('shop_style', '=', 1);
                    })->first();
                    if ((!empty($apply_check) && in_array($apply_check->status, [0, 1, 2]))) {
                        throw new BusinessException(ErrorCode::NORMAL_ERROR, '无法申请,申请审核中');
                    }
                    $apply_type = $filter_data['params']['apply_type'] = $filter_data['params']['type'];
                } else {
                    // 验证待完善的申请单
                    $my_applying = $this->flyShopApply->getInstance()
                        ->where(['user_id' => $user_id, 'status' => 0])
                        ->select(['id', 'apply_type'])
                        ->first();

                    if (empty($my_applying)) {
                        throw new BusinessException(ErrorCode::NORMAL_ERROR, '请先完善基本信息');
                    }
                    $filter_data['params']['apply_id'] = $my_applying->id;
                    $filter_data['params']['apply_type'] = $my_applying->apply_type;
                    $apply_type = $my_applying->apply_type;
                }
                // 认证类型
                $filter_data['params']['cert_type'] = $apply_type == 1 ? 1 : 2;

                $img_type = ['jpg', 'jpeg', 'png'];
                // 认证类型 - 个人
                if ($apply_type == 1) {
                    if (empty($filter_data['params']['id_name']) || empty($filter_data['params']['id_number'])) {
                        throw new BusinessException(ErrorCode::NORMAL_ERROR, '认证信息填写不完整');
                    }

                    $id_front = $this->fileinfo->getFileinfo($filter_data['params']['id_front_id'] ?? 0);// 身份证正面
                    $id_back = $this->fileinfo->getFileinfo($filter_data['params']['id_back_id'] ?? 0);// 身份证反面
                    if ((empty($id_front) || empty($id_back))) {
                        throw new BusinessException(ErrorCode::NORMAL_ERROR, '当前认证为个人，请上传身份证信息');
                    }
                    if ($id_front[0]['user_id'] !== $user_id || $id_back[0]['user_id'] !== $user_id) {
                        throw new BusinessException(ErrorCode::NORMAL_ERROR, '非法提交，请重新上传身份证信息');
                    }
                    if (!in_array($id_front[0]['imagetype'], $img_type) || !in_array($id_back[0]['imagetype'], $img_type)) {
                        throw new BusinessException(ErrorCode::NORMAL_ERROR, '身份证图片格式错误');
                    }
                    $filter_data['params']['fileinfo']['id_front'] = $id_front[0];
                    $filter_data['params']['fileinfo']['id_back'] = $id_back[0];
                } else {
                    // 判断是否已上传过营业执照（已上传如不变更 不需再次上传）
                    $shop_id = $this->getMyShop($user_id)['shop_id'] ?? 0;
                    if (empty($this->certAtt->getCertTypeByCertID($shop_id, FlyShopCertificateService::TYPE_LICENSE)) && (empty($filter_data['params']['fullname']) || empty($filter_data['params']['cert_number']))) {
                        throw new BusinessException(ErrorCode::NORMAL_ERROR, '认证信息填写不完整');
                    }

                    // 获取图片
                    $license = $this->fileinfo->getFileinfo($filter_data['params']['license_id'] ?? 0);// 营业执照
                    if (empty($license) || $license[0]['user_id'] != $user_id) {
                        throw new BusinessException(ErrorCode::NORMAL_ERROR, '当前认证为企业，请上传证书');
                    } elseif (!in_array($license[0]['imagetype'], $img_type)) {
                        throw new BusinessException(ErrorCode::NORMAL_ERROR, '证书图片格式错误');
                    }
                    $filter_data['params']['fileinfo']['license'] = $license[0];
                }

            } else {
                // 商家信息修改单
                // 如果原来是个人 不可将申请类型改为其他
                $shop_old = $this->flyShop->getMyShop($user_id);
                if (empty($shop_old)) {
                    throw new BusinessException(ErrorCode::NORMAL_ERROR, '未获取到店铺信息');
                }
                // 获取审核通过最新申请状态
                if (!$this->flyShopApply->getInstance()->where(['user_id' => $user_id, 'status' => 2])->exists()) {
                    throw new BusinessException(ErrorCode::NORMAL_ERROR, '非法操作，入驻未审核');
                }
                if ($shop_old['type'] == 4 && $filter_data['params']['type'] != 4) {
                    throw new BusinessException(ErrorCode::NORMAL_ERROR, '认证信息不可修改，入驻认证为个人');
                } elseif ($shop_old['type'] != 4 && $filter_data['params']['type'] == 4) {
                    throw new BusinessException(ErrorCode::NORMAL_ERROR, '认证信息不可修改，入驻认证为企业');
                }
            }
        }
        $filter_data['params']['apply_order_type'] = $type;
        $filter_data['params']['address_info'] = $filter_data['params']['address_info'] ?? "";
        return [
            'res' => $res,
            'msg' => $msg,
            'join_in_flag' => $join_in_flag,
            'data' => $filter_data['params']
        ];
    }

    /**
     * 获取申请单状态
     * @param int $user_id
     * @param int $style_type 1电商 2美食
     * @return array
     */
    public function getApplyState(int $user_id, int $style_type): array
    {
        $apply = $this->flyShopApply->getApplyNow($user_id, $style_type);
        return [
            'status' => empty($apply) ? 4 : $apply['status'], // 申请单状态
            'apply_type' => $apply['apply_type'] ?? 0,
            'shop_type' => !empty($apply['apply_info']) ? $apply['apply_info']['shop_type'] : 0
        ];
    }

    /**
     * 获取当前申请单状态
     * @param int $user_id
     * @param int $style_type
     * @return array
     */
    public function getApplyNow(int $user_id, int $style_type): array
    {
        $applying = $this->flyShopApply->getApplyNow($user_id, $style_type);
        if (!empty($applying) && !empty($applying['apply_info'])) {
            if (!empty($applying['apply_info']['figure_urls'])) {
                $applying['apply_info']['figure_urls_arr'] = json_decode($applying['apply_info']['figure_urls'], true);
            } else {
                $applying['apply_info']['figure_urls_arr'] = [];
            }
            $applying['apply_info']['dc_arr'] = empty($applying['apply_info']['dc_list']) ? [] : json_decode($applying['apply_info']['dc_list']);
            $applying['apply_info']['figure_ids_arr'] = empty($applying['apply_info']['figure_ids']) ? [] : json_decode($applying['apply_info']['figure_ids']);
        }
        return $applying;
    }

    /**
     * 申请提交
     * @param array $params
     * @return bool
     */
    public function apply_submit(array $params): bool
    {
        Db::beginTransaction();
        // 申请入驻 || 修改信息重新入驻
        if ($params['apply_order_type'] == 1 || $params['apply_order_type'] == 4) {

            if ($params['apply_order_type'] == 4) {
                $my_shop = $this->flyShop->getMyShop($params['user_id']);
                if (empty($my_shop)) {
                    Db::rollBack();
                    return false;
                }
                $params['shop_id'] = $my_shop['id'];
            } else {
                // 未入驻过任何类型的店铺是需要先保存商家店铺，若已入驻：对基本信息修改需要审核通过后生效
                $joined_shop = $this->flyShop->getMyShop($params['user_id']);
                if (empty($joined_shop)) {
                    // 保存商家基本信息
                    $shop_id = $this->flyShop->saveShopBaseInfo($params);
                    if (!$shop_id) {
                        Db::rollBack();
                        return false;
                    }
                    $params['shop_id'] = $shop_id;
                } else {
                    // 已入驻的美食店铺：需保存入驻类型，需要体现入驻标识（店铺基本信息审核后修改）
                    if (!$this->flyShop->updateShopBase(['shop_type' => $params['shop_type']], $joined_shop['id'])) {
                        Db::rollBack();
                        throw new BusinessException(ErrorCode::NORMAL_ERROR, '入驻类型绑定失败');
                    }
                    $params['shop_id'] = $joined_shop['id'];
                }
            }
            // 创建申请单
            $apply_d = $this->flyShopApply->createApplyOrder($params);
            if (!$apply_d) {
                Db::rollBack();
                return false;
            }
            // 保存申请单基本信息
            $params['apply_id'] = $apply_d;
            $res = $this->flyShopApplyInfo->saveApplyInfo($params);
            if (!$res) {
                Db::rollBack();
                return false;
            }
        } else {
            // 完善信息 || 修改信息 (todo 后台审核后更新到商家信息补充里面
//            $this->flyShop->saveShopSupInfo($params);
            // 修改信息申请生成申请单
            if ($params['apply_order_type'] == 3) {
                $apply_d = $this->flyShopApply->createApplyOrder($params);
                if (!$apply_d) {
                    DB::rollBack();
                    return false;
                }
                $params['apply_id'] = $apply_d;
            } else {
                // 完善信息更新原申请单
                $res = $this->flyShopApply->saveApplyOrder(['status' => 1, 'apply_time' => time()], $params['apply_id']);
                if (!$res) {
                    Db::rollBack();
                    return false;
                }
            }
            $res = $this->flyShopApplyInfo->saveApplyInfo($params);
            if (!$res) {
                Db::rollBack();
                return false;
            }
        }
        Db::commit();
        return true;
    }

    /**
     * 升级云店商城
     * @param $user_id
     * @return bool
     */
    public function merchant_upgrade($user_id): bool
    {
        // 获取店铺类型
        $myShop = $this->flyShop->getMyShop($user_id);
        if (empty($myShop)) {
            // 未查询到我的店铺信息
            return false;
        }
        if ($myShop['shop_type'] == 2) {
            // 已经是云店商城 不需要升级
            return false;
        }
        $refuse_flag = 0;
        $lately_check_time = $lately_apply_id = 0;
        foreach ($myShop['with_join_order'] as $join_order) {
            if ($join_order['status'] == 3) {
                $refuse_flag++;
            }
            if (in_array($join_order['status'], [0, 1])) {
                // 存在草稿 或 待审核的申请单
                return false;
            }
            // 获取最近一次通过的申请信息 作为本次升级参数
            if ($join_order['status'] == 2 && $join_order['check_time'] > $lately_check_time) {
                $lately_check_time = $join_order['check_time'];
                $lately_apply_id = $join_order['id'];
            }
        }
        if (count($myShop['with_join_order']) == $refuse_flag) {
            // 所有申请均未通过
            return false;
        }
        $apply_info = $this->flyShopApplyInfo->getApplyInfo($lately_apply_id);
        if (empty($apply_info) || $apply_info['shop_type'] != 1) {
            // 申请单详情不存在
            return false;
        }
        $apply_data = [
            'shop_id' => $myShop['id'],
            'user_id' => $user_id,
            'apply_time' => time(),
            'type' => $myShop['type'],
            'status' => 1,
            'apply_order_type' => 5// 升级云商城
        ];
        Db::beginTransaction();

        try {
            $apply_id = $this->flyShopApply->createApplyOrder($apply_data);
            if (!$apply_id) {
                // 保存申请单失败
                Db::rollBack();
                return false;
            }
            $apply_info['apply_id'] = $apply_id;
            $apply_info['apply_order_type'] = 5;// 升级
            $apply_info['user_id'] = $user_id;
            $apply_info['shop_type'] = 2; // 升级云商城
            $apply_info_res = $this->flyShopApplyInfo->saveApplyInfo($apply_info);
            if (!$apply_info_res) {
                // 保存申请详情失败
                return false;
            }
        } catch (\Throwable $exception) {
            print_r($exception->getMessage());
            Db::rollBack();
            return false;
        }
        Db::commit();
        return true;
    }

    /**
     * 非商城入驻申请
     * @param int $user_id
     * @param array $params
     * @param int $style_type 2餐饮
     * @param int $submit_type 验证类型：1基本信息填写 2信息完善 4修改重新入驻
     * @return bool
     */
    public function otherJoinApply(int $user_id, array $params, $style_type = FlyShopService::STYLE_TYPE_FOOD, $submit_type = 1): bool
    {
        if (!in_array($style_type, [FlyShopService::STYLE_TYPE_FOOD])) {
            throw new BusinessException(ErrorCode::NORMAL_ERROR, '入驻模块选择错误');
        }

        $base_info = ['shop_name', 'link_name', 'phone', 'address_locate', 'address_info', 'lat', 'lng'];
        $details_info = ['id_name', 'id_number', 'fullname', 'cert_number', 'license_id', 'food_license', 'figure_ids', 'gender', 'id_address', ' birthday', 'issuing_agency', 'valid_start_date', 'valid_end_date', 'business_term', 'capital_social', 'corp', 'register_address'];
        $base_rule = [
            'shop_name' => ['required', 'max:150'],
            'link_name' => ['required', 'max:32'],
            'phone' => ['required', 'max:20'],
            'address_locate' => ['required', 'max:150'],
            'lat' => ['numeric', 'min:-90', 'max:90'],
            'lng' => ['numeric', 'min:-180', 'max:180']
        ];
        $details_rule = [
            'license_id' => ['required', 'integer'],
            'food_license' => ['required', 'integer'],
            'figure_ids.*' => ['required', 'integer'],
        ];
        // 基本信息
        $filter_arr = $rule = [];
        switch ($submit_type) {
            case 1:// 基本信息
                $filter_arr = $base_info;
                $rule = $base_rule;
                break;
            case 2:// 信息完善
                switch ($style_type) {
                    case FlyShopService::STYLE_TYPE_FOOD:
                        $filter_arr = $details_info;
                        $rule = $details_rule;
                        break;
                }
                break;
            case 4:// 修改重新入驻
                $filter_arr = array_merge($base_info, $details_info);
                $rule = array_merge($base_rule, $details_rule);
                break;
        }
        $ret = array_filter($params, function ($k) use ($filter_arr) {
            if (!in_array($k, $filter_arr)) {
                return false;
            } else {
                return true;
            }
        }, ARRAY_FILTER_USE_KEY);

        $validator = $this->validator->make($ret, $rule);
        if ($validator->fails()) {
            throw new BusinessException(ErrorCode::NORMAL_ERROR, $validator->errors()->first());
        }

        $current = $this->getApplyNow($user_id, FlyShopService::STYLE_TYPE_FOOD);
        if ($submit_type == 1) {
            // 重新入驻填写基本信息
            if (!empty($current) && $current['status'] != 3) {
                throw new BusinessException(ErrorCode::NORMAL_ERROR, '重复操作已入驻');
            }
        } elseif ($submit_type == 2) {
            if (empty($current)) {
                throw new BusinessException(ErrorCode::NORMAL_ERROR, '请先填写基本信息');
            } elseif ($current['status'] != 0) {
                throw new BusinessException(ErrorCode::NORMAL_ERROR, '状态错误,请先填写基本信息');
            }
        } elseif ($submit_type == 4) {
            if (empty($current)) {
                throw new BusinessException(ErrorCode::NORMAL_ERROR, '入驻申请不存在');
            } elseif ($current['status'] != 3) {
                throw new BusinessException(ErrorCode::NORMAL_ERROR, '状态错误');
            }
        } else {
            throw new BusinessException(ErrorCode::NORMAL_ERROR, '违规操作');
        }

        $my_shop = $this->flyShop->getMyShop($user_id);
        // 名称重复验证
        if ($submit_type != 2) {
            // 已入驻过云店或商城或美食基本信息已填写
            $except = ($submit_type == 4 || !empty($my_shop));
            if ($this->flyShop->checkShopName($ret['shop_name'], $except, $user_id)) {
                throw new BusinessException(ErrorCode::NORMAL_ERROR, '店铺名已存在');
            }
        }

        // 完善信息或入驻 文件验证
        if (!empty($ret['license_id'])) {
            $license = $this->fileinfo->getFileinfo([$ret['license_id']]);
            $food_license = $this->fileinfo->getFileinfo([$ret['food_license']]);
            $figures = $this->fileinfo->getFileinfo($ret['figure_ids']);
            if (empty($license) || empty($food_license) || $license[0]['user_id'] != $user_id || $food_license[0]['user_id'] != $user_id) {
                throw new BusinessException(ErrorCode::NORMAL_ERROR, '证书文件无效');
            }
            $ret['license_url'] = $license[0]['url'];
            $ret['food_license_url'] = $food_license[0]['url'];
            foreach ($figures as $item) {
                if ($item['user_id'] = $user_id) {
                    $ret['figure_arr'][] = ['fileinfo_id' => $item['fileinfo_id'], 'url' => $item['url']];
                }
            }
        }
        if (!empty($ret['figure_ids'])) {
            $f_json = json_encode($ret['figure_ids']);
            $f_arr = json_encode($ret['figure_arr']);
            unset($ret['figure_ids'], $ret['figure_arr']);
            $ret['figure_ids'] = $f_json;
            $ret['figure_urls'] = $f_arr;
        }
        // 完善信息 获取入驻申请模型
        Db::beginTransaction();

        // 申请单实例
        if ($submit_type == 2) {
            $base_instance = $this->flyShopApply->getInstance()
                ->where('user_id', '=', $user_id)
                ->where('shop_style', '=', $style_type)// 美食类型入驻
                ->where('status', '=', FlyShopApplyService::STATUS_DRAFT)
                ->first();
            if (empty($base_instance) || empty($base_instance->toArray())) {
                Db::rollBack();
                throw new BusinessException(ErrorCode::NORMAL_ERROR, '请填写基本信息');
            }
        } else {
            // 填写基本信息或重新入驻 生成新入驻申请模型
            $base_instance = $this->flyShopApply->getInstance();
            $base_instance->user_id = $user_id;
            $base_instance->apply_time = time();
            $base_instance->apply_type = 2;
            $base_instance->shop_style = FlyShopService::STYLE_TYPE_FOOD;//todo 美食类型的店铺入驻申请
        }
        $base_instance->apply_order_type = $submit_type;// 申请单类型
        $base_instance->status = $submit_type == 1 ? 0 : 1;

        $ret['user_id'] = $user_id;
        // 基本信息
        if ($submit_type == 1) {
            $ret['food_switch'] = 1;
            // 先入驻美食
            if (empty($my_shop)) {
                $shop_id = $this->flyShop->saveShopBaseInfo($ret, true);
                if (empty($shop_id)) {
                    Db::rollBack();
                    throw new BusinessException(ErrorCode::NORMAL_ERROR, '保存店铺失败');
                }
            } else {
                // 先入驻云店后
                if (!$this->flyShop->updateShopBase(['food_switch' => 1], $my_shop['id'])) {
                    Db::rollBack();
                    throw new BusinessException(ErrorCode::NORMAL_ERROR, '加盟店铺失败');
                }
                $shop_id = $my_shop['id'];
            }
        } else {
            $shop_id = $my_shop['id'];
        }
        $base_instance->shop_id = $shop_id;

        if (!$base_instance->save()) {
            Db::rollBack();
            return false;
        }
        $ret['cert_type'] = FlyShopCertificate::CERT_TYPE_COM;
        $ret['apply_id'] = $base_instance->id;
        $ret['shop_style'] = $style_type;
        // 申请单详情实例
        if (in_array($submit_type, [1, 4])) {
            $instance = make(FlyShopApplysInfo::class);
        } else {
            $instance = make(FlyShopApplysInfo::class)->where('apply_id', '=', $ret['apply_id'])->first();
            if (empty($instance) || empty($instance->toArray())) {
                Db::rollBack();
                throw new BusinessException(ErrorCode::NORMAL_ERROR, '入驻记录不存在');
            }
        }
        // 完善信息补充信息容错
        if ($submit_type == 2 || $submit_type == 4) {
            $ret['gender'] = empty($params['gender']) ? 0 : (int)$params['gender'];
            $ret['id_address'] = $params['id_address'] ?? "";
            $ret['birthday'] = $params['birthday'] ?? null;
            $ret['issuing_agency'] = $params['issuing_agency'] ?? "";
            $ret['valid_start_date'] = $params['valid_start_date'] ?? null;
            $ret['valid_end_date'] = $params['valid_end_date'] ?? null;
            $ret['business_term'] = $params['business_term'] ?? "";
            $ret['capital_social'] = $params['capital_social'] ?? "";
            $ret['corp'] = $params['corp'] ?? "";
            $ret['register_address'] = $params['register_address'] ?? "";
        }

        unset($ret['food_switch'], $ret['user_id']);
        $ret['apply_user_id'] = $user_id;
        foreach ($ret as $field => $value) {
            $instance->$field = $value;
        }
        // 保存申请单详情
        if (!$instance->save()) {
            Db::rollBack();
            return false;
        }

        Db::commit();
        return true;
    }


    /**
     * 过滤无效参数
     * @param array $params
     * @param int $filter_type 验证类型 1入驻申请 2信息完善 3商家申请修改信息 4修改重新入驻
     * @return array 验证参数
     */
    public function merchant_filter_params(array $params, int $filter_type = 1): array
    {
        // 基本信息
        $base_fields = ['shop_name', 'type', 'link_name', 'phone', 'shop_type', 'address_locate', 'address_info', 'lat', 'lng'];
        // 完善信息
        $complete_info = ['dc_id', 'license_id', 'id_front_id', 'id_back_id', 'fullname', 'id_name', 'id_number', 'cert_number', 'cert_type', 'figure_ids'
            , 'gender', 'id_address', 'birthday', 'issuing_agency', 'issuing_agency', 'valid_start_date', 'valid_end_date', 'business_term', 'capital_social', 'corp', 'register_address'];
        // 商家认证信息修改
        $modify_info = ['shop_name', 'type', 'link_name', 'phone', 'shop_type', 'address_locate', 'industry_ids', 'dc_ids', 'figure_ids'];
        // 商家重新入驻
        $apply_modify_info = array_merge($base_fields, $complete_info);
        foreach ($params as $field => $value) {
            switch ($filter_type) {
                case 1:
                    // 过滤非基本信息
                    if (!in_array($field, $base_fields)) {
                        unset($params[$field]);
                    }
                    break;
                case 2:
                    // 过滤基本信息
                    if (!in_array($field, $complete_info)) {
                        unset($params[$field]);
                    }
                    break;
                case 3:
                    // 过滤不能修改的信息
                    if (!in_array($field, $modify_info)) {
                        unset($params[$field]);
                    }
                    break;
                case 4:
                    if (!in_array($field, $apply_modify_info)) {
                        unset($params[$field]);
                    }
                    break;
                default:
                    break;
            }
        }

        if ($filter_type == 1) {// 基本信息
            $rules = [
                'type' => Rule::in([1, 2, 3, 4]),
                'shop_name' => ['required', 'max:255'],
                'link_name' => ['required', 'max:32'],
                'phone' => ['required'],
                'shop_type' => [Rule::in([1, 2])],
                'address_locate' => ['required', 'max:150'],
                'address_info' => ['nullable', 'max:150'],
                'apply_order_type' => Rule::in([1, 2, 3]),// 1入驻 2完善 3商家信息修改 4修改重新入驻
                'lat' => ['required'],//维度
                'lng' => ['required']//经度
            ];
        } elseif ($filter_type == 2) { // 完善信息
            $rules = [
//                'industry_ids' => ['required', 'array'],
                'dc_id' => ['required', 'integer'],
                'license_id' => ['nullable', 'integer'],
                'id_front_id' => ['nullable', 'integer'],
                'id_back_id' => ['nullable', 'integer'],
                'id_name' => ['nullable', 'max:32'], // 用户认证身份证名称
                'id_number' => ['nullable', 'max:32'], // 身份证号
                'fullname' => ['nullable', 'max:32'], // 营业执照认证企业名称
                'cert_number' => ['nullable', 'max:64'], // 企业信用代码
                'cert_type' => [Rule::in([1, 2])],
                'apply_order_type' => Rule::in([1, 2, 3])
            ];
        } elseif ($filter_type == 3) { // 商家申请信息修改
            $rules = [
                'type' => Rule::in([1, 2, 3, 4]),
//                'industry_ids' => ['required', 'array'],
                'dc_id' => ['required', 'integer'], // todo 集散地改为一个（dc_ids=>dc_id）
                'shop_name' => ['required', 'max:255'],
                'link_name' => ['required', 'max:32'],
                'phone' => ['required'],
                'shop_type' => Rule::in([1, 2]),// 升级为云店
                'address_locate' => ['required', 'max:150'],
                'lat' => ['required'],//维度
                'lng' => ['required'],//经度
                'apply_order_type' => Rule::in([1, 2, 3])
            ];
        } else { // 修改重新入驻
            $rules = [
                'type' => Rule::in([1, 2, 3, 4]),
                'dc_id' => ['required', 'integer'],
                'shop_name' => ['required', 'max:255'],
                'link_name' => ['required', 'max:32'],
                'phone' => ['required'],
                'shop_type' => [Rule::in([1, 2])],
                'address_locate' => ['required', 'max:150'],
                'address_info' => ['nullable', 'max:150'],
                'lat' => ['required'],//维度
                'lng' => ['required'],//经度
                'license_id' => ['nullable', 'integer'],
                'id_front_id' => ['nullable', 'integer'],
                'id_back_id' => ['nullable', 'integer'],
                'fullname' => ['nullable', 'max:32'],
                'cert_number' => ['nullable', 'max:64'],
                'id_name' => ['nullable', 'max:32'],
                'id_number' => ['nullable', 'max:32'],
                'cert_type' => [Rule::in([1, 2])],
                'apply_order_type' => Rule::in([1, 2, 3, 4])
            ];
        }
        return ['params' => $params, 'rules' => $rules];
    }

    /**
     * 申请更新商家基本信息
     * @param array $params
     * @return bool
     */
    public function modifyShop(array $params): bool
    {
        $res = $this->flyShopApply->createApplyOrder($params);
        if (!$res) {
            return false;
        }
        $data = $this->flyShopApplyInfo->getApplyData($params);
        return $this->flyShopApplyInfo->saveApplyInfo($data);
    }

    /**
     * 获取我的店铺信息
     * @param int $user_id
     * @return array
     */
    public function getMyShop(int $user_id): array
    {
        $shop = $this->flyShop->getShopInfoByUserId($user_id);
        if (empty($shop)) {
            return [];
        }
        return [
            'shop_id' => $shop['id'],
            'shop_name' => $shop['shop_name'],
            'address_locate' => $shop['address_locate'],
            'address_info' => $shop['address_info'] ?? "",
            'lng' => $shop['lng'],
            'lat' => $shop['lat'],
            'link_name' => $shop['link_name'],
            'phone' => $shop['phone'],
            'license' => $this->certAtt->getCertTypeByCertID($shop['id'], FlyShopCertificateService::TYPE_LICENSE),
            'figures' => $this->certAtt->getCertTypeByCertID($shop['id'], FlyShopCertificateService::TYPE_FIGURES)
        ];
    }
}